package com.xyzq.hs;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.xyzq.hs.util.Logger;
import com.xyzq.hs.util.LoggerFactory;

public class ListResultSetCallBack implements ResultSetCallBack{
	
	Logger log=LoggerFactory.getLogger(ListResultSetCallBack.class);
	
	private Class<?> clazz;

	public <T> ListResultSetCallBack(Class<?> clazz) {
		super();
		this.clazz=clazz;
	}
	
	@Override
	public Object doInResultSet(ResultSet rs) throws TSException {
		try {
			List<Object> list=new ArrayList<Object>();
			while(rs.next()){
				Object o = Class.forName(clazz.getName()).newInstance();
				Field[] fields = clazz.getDeclaredFields();
				ResultSetMetaData meta = rs.getMetaData();
				for(Field f:fields){
					String columnName = f.getName();
					Short columnIndex = meta.getColumnIndex(columnName);
					if(columnIndex==null){
						continue;
					}
					Class<?> type = f.getType();
					String typeName = type.getSimpleName();
					f.setAccessible(true);
					try {
						if("short".equalsIgnoreCase(typeName)){
							f.set(o, rs.getShort(columnIndex));
						}else if("int".equalsIgnoreCase(typeName)){
							f.set(o,rs.getInt(columnIndex));
						}else if("Integer".equalsIgnoreCase(typeName)){
							f.set(o,rs.getInt(columnIndex));
						}else if("long".equalsIgnoreCase(typeName)){
							f.set(o, rs.getLong(columnIndex));
						}else if("float".equalsIgnoreCase(typeName)){
							f.set(o, rs.getFloat(columnIndex));
						}else if("double".equalsIgnoreCase(typeName)){
							f.set(o, rs.getDouble(columnIndex));
						}else if("string".equalsIgnoreCase(typeName)){
							f.set(o, rs.getString(columnIndex));
						}else if("BigDecimal".equalsIgnoreCase(typeName)){
							f.set(o, new BigDecimal(rs.getString(columnIndex)));
						}else{
							f.set(o, rs.getShort(columnIndex));
						}
					} catch (Exception e) {
						throw new TSException(clazz.getName()+" "+columnName+" "+typeName+","+e.getMessage());
					}
				}
				list.add(o);
			}
			return list;
		} catch (Exception e) {
			throw new TSException(e.getMessage());
		}
	}

}
